<!--
 * @Author: your name
 * @Date: 2021-05-26 17:15:56
 * @LastEditTime: 2021-06-06 21:53:50
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \遵义报名\zunyi\src\components\uoload.vue
-->
<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :auto-upload="false"
      :on-change="beforeAvatarUpload"
      accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
      :limit="1"
      :class="fileList.length ? 'show' : null"
      :file-list="fileList"
    >
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{ file }">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <!-- 放大 -->
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>

          <!-- 删除 -->
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>

    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  props:{
    currentBase64Img:{
      type:String,
      required:true
    }
  },
  model:{
    prop:"currentBase64Img",
    event:"change"
  },
  data() {
    return {
      dialogImageUrl: "", //放大的图片
      dialogVisible: false,
      disabled: false,
      fileList:this.currentBase64Img ? [{url:this.currentBase64Img}] : [],//文件列表
    };
  },
  methods: {
    handleRemove() {
      //删除图片
      this.fileList.splice(0,1)
    },
    handlePictureCardPreview(file) {
      //放大图片
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    isValidator(file){//校验
      const isJPG = file.raw.type === "image/jpeg" | file.raw.type === "image/jpg" | file.raw.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!"); 
      }

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    async beforeAvatarUpload(file,fileList) {//上传之前的限制
      let res = await this.$getBase64(file.raw)
      this.fileList = fileList

      // console.log(this.fileList)
      // this.fileList = JSON.parse(JSON.stringify(fileList))
      if(this.isValidator(file)){
        this.$emit("change",res)
      }else{
        fileList.splice(0,1)
      }
      
    },
  },
};
</script>

<style lang="scss" scoped>
.show {
  /deep/ .el-upload,.el-upload--picture-card {
    display: none;
  }
}
</style>